package alvarodelrosal.chat.client.gui;

import alvarodelrosal.chat.client.chataction.remote.ChatChat;
import alvarodelrosal.chat.client.chataction.remote.ChatBye;
import alvarodelrosal.chat.client.chataction.remote.ChatGetAllUsers;
import alvarodelrosal.chat.client.chataction.remote.ChatAllMyChats;
import alvarodelrosal.chat.client.chataction.remote.ChatMyChats;
import alvarodelrosal.chat.client.chataction.remote.ChatByeChat;
import alvarodelrosal.chat.client.chataction.remote.ChatNewChat;
import alvarodelrosal.chat.client.chataction.remote.ChatAllChats;
import alvarodelrosal.chat.client.chataction.infraestructuraremota.OnlineConversations;
import alvarodelrosal.chat.client.modelo.ChatUser;
import alvarodelrosal.chat.client.modelo.Conversation;
import java.util.List;
import java.util.Set;
import javax.swing.SwingUtilities;

public class MainWindow extends javax.swing.JFrame {

    public static void addConversation(Conversation conversation) {
        jComboBox1.addItem(conversation);
        jComboBox1.setSelectedIndex(-1);
    }

    public static void removeAllConversations() {
        jComboBox1.removeAllItems();
    }

    public static void setUser(ChatUser user) {
        MainWindow.user = user;
    }
    private static ChatUser user;

    public MainWindow() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("miniChat");
        setSize(new java.awt.Dimension(800, 600));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                ChatsUpdater(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                CloseHandler(evt);
            }
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jButton2.setText("Nuevo chat");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);

        jButton3.setText("Actualizar chats");
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton3);

        jButton4.setText("Invitar al chat");
        jButton4.setFocusable(false);
        jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton4);

        jButton5.setText("Historial de conversaciones");
        jButton5.setFocusable(false);
        jButton5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton5);

        jButton6.setText("Administrar usuarios");
        jButton6.setFocusable(false);
        jButton6.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton6.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton6);

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jTextArea1.setDragEnabled(false);
        jTextArea1.setFocusTraversalKeysEnabled(false);
        jTextArea1.setFocusable(false);
        jTextArea1.setRequestFocusEnabled(false);
        jTextArea1.setVerifyInputWhenFocusTarget(false);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Enviar");
        jButton1.setSelected(true);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jToolBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .add(jTextField1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton1))
            .add(jComboBox1, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jToolBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 25, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton1)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        String asunto = Dialogo.pintarCuadroDeDialogo("Nuevo Chat", "Introduzca el asunto del nuevo chat");
        if (esValidoEl(asunto)) {
            ChatNewChat newChat = new ChatNewChat();
            List<String> parameters = newChat.generateParameters(asunto);
            newChat.doAction(parameters);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        removeAllConversations();
        ChatMyChats chats = new ChatMyChats();
        chats.doAction(null);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (esValidoEl(jTextField1.getText())) {
            ChatChat chat = new ChatChat();
            Conversation conversation = (Conversation) jComboBox1.getSelectedItem();
            List<String> parameters = chat.prepareParameters(conversation.getId(), jTextField1.getText());
            chat.doAction(parameters);
            jTextField1.setText("");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        ChatGetAllUsers online = new ChatGetAllUsers();
        online.doAction(null);

        if (jComboBox1.getSelectedIndex() != -1) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    Conversation conversation = (Conversation) jComboBox1.getSelectedItem();
                    InvitarAUsuarios usuarios = new InvitarAUsuarios(conversation);
                    usuarios.setVisible(true);
                }
            });
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        updateChats();
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void CloseHandler(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_CloseHandler
        Set<Conversation> allConversations = OnlineConversations.getAllConversations();
        for (Conversation conversation : allConversations) {
            ChatByeChat byeChat = new ChatByeChat();
            List<String> parameters = byeChat.prepareParameters(conversation.getId());
            byeChat.doAction(parameters);
        }

        ChatBye bye = new ChatBye();
        bye.doAction(null);
    }//GEN-LAST:event_CloseHandler

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        CloseHandler(evt);
    }//GEN-LAST:event_formWindowClosed

    private void ChatsUpdater(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_ChatsUpdater
        removeAllConversations();
        ChatMyChats chats = new ChatMyChats();
        chats.doAction(null);
    }//GEN-LAST:event_ChatsUpdater

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        if (user.isAdmin()) {
            ChatAllChats chats = new ChatAllChats();
            chats.doAction(null);
        } else {
            ChatAllMyChats chats = new ChatAllMyChats();
            chats.doAction(null);
        }
        
        new ListaDeChats().setVisible(true);
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        if(user.isAdmin()) {
            new AdministrarUsuarios().setVisible(true);
        } else {
            Dialogo.pintarMensajeDeError("Error", "No tiene suficientes privilegios para realizar esta accion");
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private static javax.swing.JComboBox jComboBox1;
    private javax.swing.JScrollPane jScrollPane1;
    private static javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables

    public static void updateChats() {
        Conversation conversation = (Conversation) jComboBox1.getSelectedItem();
        if (conversation != null) {
            jTextArea1.setText(conversation.getMessagesAsString());
        }
    }

    private boolean esValidoEl(String asunto) {
        return asunto != null && !"".equals(asunto);
    }
}
